const app = getApp()
const WXAPI = require('../../wxapi/main')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: null,
    changeAvatarUrl: null,
    userInfo: null,
    ApiBaseUrl: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    that.setData({
      ApiBaseUrl: app.globalApi.baseUrl,
    })
    // let that = this
    that.loadUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  loadUserInfo: function() {
    let that = this
    let skey = wx.getStorageSync('loginFlag')
    if (skey) {
      WXAPI.loadUser({skey})
      .then(res => {
        console.log('res ', res)
        if (res.code === 0) {
          that.setData({
            userInfo: res.data,
            avatarUrl: res.data.avatar
          })
        }
      })
    }
  },
  changeAvatar: function() {
    let that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log('rs ',res)
        console.log(res.tempFiles[0].tempFilePath)
        console.log(res.tempFiles[0].size)
        that.setData({
          avatarUrl: null,
          changeAvatarUrl: res.tempFiles[0].tempFilePath
        })
      }
    })

   
  },

  uploadFile: function() {
    let that = this
    if (!that.data.userInfo) {
      wx.showToast({
        title: '尚未登录',
        icon: 'error'
      })
      return
    }
    console.log('current openId ', that.data.userInfo.openId)
    if (! that.data.changeAvatarUrl) {
      wx.showToast({
        title: '请选择头像',
        icon: 'error'
      })
      return
    }
    wx.uploadFile({
      url: that.data.ApiBaseUrl + '/upload', //仅为示例，非真实的接口地址
      filePath: that.data.changeAvatarUrl,
      header: {"Content-Type": "multipart/form-data" },
      name: 'file',
      formData: {
        'openId': that.data.userInfo.openId
      },
      success (res){
        const data = res.data
        console.log('data ', data)
        if (data=='SUCCESS') {
          wx.showToast({
            title: '更新头像成功',
            icon: 'success'
          })
          wx.switchTab({
            url: '/pages/my/index',
          })
        }
        //do something
      },
      fail (err) {
        console.log(err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // let that = this
    // that.loadUserInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})